﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "工序管理";
    Layout = null;
}

@Html.AntiForgeryToken()

<!-- 先加载CSS -->
<link href="https://cdn.bootcdn.net/ajax/libs/layui/2.6.8/css/layui.min.css" rel="stylesheet">

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-header">
            <h3>工序管理</h3>
        </div>
        <div class="layui-card-body">
            <form class="layui-form" action="">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">工序编码</label>
                        <div class="layui-input-inline">
                            <input type="text" name="procedureCode" placeholder="请输入工序编码" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">工序名称</label>
                        <div class="layui-input-inline">
                            <input type="text" name="procedureName" placeholder="请输入工序名称" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">是否启用</label>
                        <div class="layui-input-inline">
                            <select name="isEnable">
                                <option value="">全部</option>
                                <option value="true">是</option>
                                <option value="false">否</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button type="submit" class="layui-btn" lay-submit lay-filter="searchForm">
                            <i class="layui-icon layui-icon-search"></i> 搜索
                        </button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>

            <div class="layui-btn-group">
                <button class="layui-btn" id="addBtn">
                    <i class="layui-icon layui-icon-add-1"></i> 添加
                </button>
                <button class="layui-btn layui-btn-danger" id="batchDeleteBtn">
                    <i class="layui-icon layui-icon-delete"></i> 批量删除
                </button>
                <button class="layui-btn layui-btn-normal" id="exportBtn">
                    <i class="layui-icon layui-icon-export"></i> 导出Excel
                </button>
            </div>

            <table id="mainTable" lay-filter="mainTable"></table>
        </div>
    </div>
</div>

<!-- 弹窗表单模板 -->
<script type="text/html" id="formTpl">
    <form class="layui-form" lay-filter="mainForm" style="margin: 20px;">
        <input type="hidden" name="Id">
        <div class="layui-form-item">
            <label class="layui-form-label required">工序编码</label>
            <div class="layui-input-block">
                <input type="text" name="ProcedureCode" required lay-verify="required" placeholder="请输入工序编码" autocomplete="off" class="layui-input">
                <div class="auto-generate-switch">
                    <span>自动生成</span>
                    <input type="checkbox" id="autoGenerateSwitch" lay-skin="switch" lay-filter="autoGenerateSwitch" lay-text="启用|禁用">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">工序名称</label>
            <div class="layui-input-block">
                <input type="text" name="ProcedureName" required lay-verify="required" placeholder="请输入工序名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">是否启用</label>
            <div class="layui-input-block">
                <input type="checkbox" name="IsEnable" lay-skin="switch" lay-text="启用|禁用" checked>
            </div>
        </div>
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <textarea name="Context" placeholder="请输入备注" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="submitForm">提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</script>

<!-- 先加载jQuery，再加载Layui -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/layui/2.6.8/layui.min.js"></script>

<script>
layui.use(['table', 'form', 'layer'], function(){
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    var $ = layui.$;
    
    // 初始化表格
    function loadTable(params) {
        var searchParams = params || {};
        searchParams.__RequestVerificationToken = $('input[name="__RequestVerificationToken"]').val();
        
        table.render({
            elem: '#mainTable',
            url: '/Procedure/List',
            method: 'post',
            where: searchParams,
            page: true,
            cols: [[
                {type: 'checkbox'},
                {field: 'id', title: 'ID', width: 80},
                {field: 'procedureCode', title: '工序编码', width: 120},
                {field: 'procedureName', title: '工序名称', width: 120},
                {field: 'isEnable', title: '是否启用', width: 100, templet: function(d){
                    return d.isEnable ? '<span class="layui-badge layui-bg-green">是</span>' : '<span class="layui-badge layui-bg-gray">否</span>';
                }},
                {field: 'context', title: '备注'},
                {fixed: 'right', title: '操作', toolbar: '#tableBar', width: 120}
            ]],
            response: {
                statusCode: 0
            },
            parseData: function(res) {
                return {
                    "code": res.code,
                    "msg": res.msg,
                    "count": res.count,
                    "data": res.data
                };
            }
        });
    }
    
    // 加载初始数据
    loadTable();
    
    // 搜索按钮点击事件
    form.on('submit(searchForm)', function(data){
        loadTable(data.field);
        return false;
    });

    // 批量删除按钮点击事件
    $('#batchDeleteBtn').on('click', function(){
        var checkStatus = table.checkStatus('mainTable');
        var data = checkStatus.data;
        if(data.length === 0){
            layer.msg('请选择要删除的记录');
            return;
        }
        
        layer.confirm('确定要删除选中的'+data.length+'条记录吗？', function(index){
            var ids = data.map(function(item){ return item.id; });
            $.ajax({
                url: '/Procedure/BatchDelete',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(ids),
                headers: {
                    'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
                },
                success: function(res){
                    if(res.code === 0){
                        layer.msg(res.msg);
                        table.reload('mainTable');
                    } else {
                        layer.msg(res.msg);
                    }
                },
                error: function(xhr){
                    layer.msg(xhr.responseJSON?.msg || '操作失败，请重试');
                }
            });
            layer.close(index);
        });
    });

    // 导出按钮点击事件
    $('#exportBtn').on('click', function(){
        var searchParams = form.val('searchForm');
        var queryString = Object.keys(searchParams)
            .filter(key => searchParams[key])
            .map(key => key + '=' + encodeURIComponent(searchParams[key]))
            .join('&');
        
        window.location.href = '/Procedure/Export?' + queryString;
    });

    // 添加按钮点击事件
    $('#addBtn').on('click', function(){
        openForm();
    });
    
    // 打开表单
    function openForm(data) {
        var title = data ? '编辑工序' : '添加工序';
        layer.open({
            type: 1,
            title: title,
            area: ['500px', '500px'],
            content: $('#formTpl').html(),
            success: function(layero, index){
                form.render(null, 'mainForm');
                
                if(data){
                    form.val('mainForm', {
                        "Id": data.id,
                        "ProcedureCode": data.procedureCode,
                        "ProcedureName": data.procedureName,
                        "IsEnable": data.isEnable,
                        "Context": data.context
                    });
                }
                
                // 绑定自动生成工序编码开关事件
                form.on('switch(autoGenerateSwitch)', function(data) {
                    if(data.elem.checked) {
                        var loadIndex = layer.load(2);
                        console.log('开始调用生成工序编码API...');
                        
                        // 调用后端生成工序编码
                        $.ajax({
                            url: '/Procedure/GenerateProcedureCode',
                            type: 'GET',
                            success: function(res) {
                                layer.close(loadIndex);
                                console.log('生成工序编码API返回结果:', res);
                                
                                if(res.code === 0 && res.procedureCode) {
                                    // 设置工序编码
                                    $('input[name="ProcedureCode"]').val(res.procedureCode);
                                    console.log('成功设置工序编码:', res.procedureCode);
                                } else {
                                    console.error('生成工序编码失败:', res);
                                    layer.msg('生成工序编码失败：' + (res.msg || '未知错误'));
                                    // 开关切回关闭状态
                                    data.elem.checked = false;
                                    form.render('checkbox');
                                }
                            },
                            error: function(xhr, status, error) {
                                layer.close(loadIndex);
                                console.error('生成工序编码请求失败:', {xhr: xhr, status: status, error: error});
                                var errorMsg = '';
                                try {
                                    if (xhr.responseJSON && xhr.responseJSON.msg) {
                                        errorMsg = xhr.responseJSON.msg;
                                    } else if (xhr.responseText) {
                                        errorMsg = xhr.responseText;
                                    } else {
                                        errorMsg = error || '服务器连接失败';
                                    }
                                } catch (e) {
                                    errorMsg = '解析错误信息失败';
                                }
                                layer.msg('生成工序编码失败：' + errorMsg);
                                // 开关切回关闭状态
                                data.elem.checked = false;
                                form.render('checkbox');
                            }
                        });
                    } else {
                        // 清空工序编码
                        $('input[name="ProcedureCode"]').val('');
                    }
                });
                
                // 监听提交
                form.on('submit(submitForm)', function(formData){
                    // 基本验证
                    if(!formData.field.ProcedureCode) {
                        layer.msg('请输入工序编码');
                        return false;
                    }
                    
                    if(!formData.field.ProcedureName) {
                        layer.msg('请输入工序名称');
                        return false;
                    }
                    
                    var isEdit = data ? true : false;
                    var loadIndex = layer.load(2);
                    
                    // 检查工序编码是否已存在
                    $.ajax({
                        url: '/Procedure/CheckProcedureCodeExists',
                        type: 'GET',
                        data: { procedureCode: formData.field.ProcedureCode },
                        success: function(checkRes) {
                            if(checkRes.code === 0) {
                                // 如果是新增，或者是编辑但编号已变更，则检查是否重复
                                var originalProcedureCode = data ? data.procedureCode : '';
                                if(checkRes.exists && (!isEdit || (isEdit && formData.field.ProcedureCode !== originalProcedureCode))) {
                                    layer.close(loadIndex);
                                    layer.msg('工序编码已存在，请更换其他编码');
                                    return;
                                }
                                
                                // 继续提交表单
                                submitForm();
                            } else {
                                layer.close(loadIndex);
                                layer.msg('检查工序编码失败：' + (checkRes.msg || '未知错误'));
                            }
                        },
                        error: function(xhr) {
                            layer.close(loadIndex);
                            layer.msg('检查工序编码失败：' + (xhr.responseJSON?.msg || '服务器错误'));
                        }
                    });
                    
                    // 提交表单方法
                    function submitForm() {
                        var submitData = {
                            ProcedureCode: formData.field.ProcedureCode,
                            ProcedureName: formData.field.ProcedureName,
                            IsEnable: formData.field.IsEnable === 'on',
                            Context: formData.field.Context || '',
                            __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
                        };
                        
                        // 如果是编辑模式，添加ID
                        if (data) {
                            submitData.Id = data.id;
                        }
                        
                        $.ajax({
                            url: data ? '/Procedure/Update' : '/Procedure/Add',
                            type: 'POST',
                            // contentType: 'application/json',
                            data: submitData,
                            success: function(res){
                                layer.close(loadIndex);
                                if(res.code === 0){
                                    layer.close(index);
                                    layer.msg(title + '成功');
                                    table.reload('mainTable');
                                } else {
                                    layer.msg(res.msg || (title + '失败'));
                                }
                            },
                            error: function(xhr){
                                layer.close(loadIndex);
                                layer.msg(xhr.responseJSON?.msg || '操作失败，请重试');
                            }
                        });
                    }
                    
                    return false;
                });
            }
        });
    }
    
    // 监听工具条
    table.on('tool(mainTable)', function(obj){
        var data = obj.data;
        if(obj.event === 'edit'){
            openForm(data);
        } else if(obj.event === 'del'){
            layer.confirm('确定要删除此工序吗？', function(index){
                $.ajax({
                    url: '/Procedure/Delete',
                    type: 'POST',
                    data: { 
                        id: data.id,
                        __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
                    },
                    success: function(res){
                        if(res.code === 0){
                            obj.del();
                            layer.msg('删除成功');
                        } else {
                            layer.msg(res.msg || '删除失败');
                        }
                    },
                    error: function(xhr){
                        layer.msg(xhr.responseJSON?.msg || '删除失败，请重试');
                    }
                });
                layer.close(index);
            });
        }
    });
});
</script>

<!-- 工具条模板 -->
<script type="text/html" id="tableBar">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<style>
.layui-form-label.required:after {
    content: '*';
    color: red;
    margin-left: 4px;
}
.layui-card {
    margin: 15px;
}
.layui-form-item {
    margin-bottom: 15px;
}

/* 自动生成开关样式 */
.auto-generate-switch {
    display: flex;
    align-items: center;
    margin-top: 8px;
}

.auto-generate-switch span {
    margin-right: 10px;
    font-size: 14px;
}

/* 自定义开关颜色为绿色 */
.layui-form-onswitch {
    background-color: #5FB878 !important;
    border-color: #5FB878 !important;
}
</style>
